//
//  YDHomeViewController.swift
//  weibo
//
//  Created by 孙亚东 on 16/6/23.
//  Copyright © 2016年 Sunyadong. All rights reserved.
//

import UIKit
import SVProgressHUD

class YDHomeViewController: YDBaseViewController {

    override func viewDidLoad() {
        
        super.viewDidLoad()

        
        if isLogin {
            
            
            loadWeiBoData()
            
            //注册View
            tableView.registerClass(YDUserStatusViewCell.self, forCellReuseIdentifier: "home")
            
            
            //设置预估行高
            
            tableView.estimatedRowHeight = 300
            
            tableView.rowHeight = UITableViewAutomaticDimension
            
            tableView.backgroundColor = UIColor(white: 240 / 255, alpha: 1)
            
            tableView.separatorStyle = UITableViewCellSeparatorStyle.None
            
//            //将下拉刷新添加到tableVies上
//            
//            tableView.addSubview(refresh)
//
//            
//            //给下拉刷新添加监听方法
//            
//            refresh.addTarget(self, action: "refreshAction:", forControlEvents: .ValueChanged)
            
            
            tableView.addSubview(ydRefresh)
            ydRefresh.addTarget(self, action: "loadWeiBoData", forControlEvents: .ValueChanged)
            
            
             //将菊花添加到footerView上
            self.tableView.tableFooterView = loadingView
            
            //让菊花开始转动
            
            loadingView.startAnimating()
            
  
        
        }else {
        
            logInView.setupInfo("关注一些人，回这里看看有什么惊喜", img: nil )
        
        }
     
        
    }
    
    
    
    //懒加载一个菊花
    
    lazy var loadingView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    
//    //懒加载下拉刷新
//    
//    lazy var refresh: UIRefreshControl = UIRefreshControl()
//
//    //实现下拉刷新的监听方法
//    func refreshAction (ref: UIRefreshControl) {
//        
//        
//        self.loadWeiBoData()
//
//        
//    }

    
    //懒加载自定义的下拉刷新
    
    lazy var ydRefresh: YDRefreshController = YDRefreshController()
    

}



//加载数据
extension YDHomeViewController {
    func loadWeiBoData () {
        
        showProgress()
        
        
        /*
        
        since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
        
        
        */
        
        var since_id = 0
        var max_id = 0
        
        since_id = YDHomeViewModel.shareInstance.StatusModels.first?.model?.id ?? 0
        
        //当菊花正在转动的时候表示加载更多
        if loadingView.isAnimating() {
        
        
            max_id = YDHomeViewModel.shareInstance.StatusModels.last?.model?.id ?? 0
            
            
            if max_id != 0 {
            
            max_id = max_id - 1
            since_id = 0
    
            }
            
        
        }

    
        YDHomeViewModel().loadData(since_id,max_id: max_id,success: { (count) -> () in
            
            
            self.hiddenProgress()
            
            self.tableView.reloadData()
            
            if !self.loadingView.isAnimating() {
                // 提示视图
                self.showMessage(count)
            }
            
            //让菊花停止转动
            self.loadingView.stopAnimating()

            
            self.ydRefresh.endRefreshing()
           
// MARK: 显示一个View，通知有多少条新加载的数据
            
            
   
            }) { () -> () in
                
                SVProgressHUD.showErrorWithStatus("加载失败")
            
        }
        

    }

}


extension YDHomeViewController {


    func showMessage(count: Int) {
    
        
        let tipLab = UILabel()
        
        tipLab.textAlignment = .Center
        
        if count == 0{
        
        tipLab.text = "没有微博更新"
        
        }else {
        
        tipLab.text = "加载\(count)条数据"
        
        }
        
        self.navigationController?.view.insertSubview(tipLab, belowSubview: (self.navigationController?.navigationBar)!)
        
        tipLab.backgroundColor = UIColor.orangeColor()
        
        
        tipLab.frame = CGRectMake(0, 20, screenWidth, 44)
        
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            
            
            var temp = tipLab.frame
            
            temp.origin.y = 64.0
            
            tipLab.frame = temp
            
            }, completion: { (Bool) -> Void in
                
                UIView.animateWithDuration(1.0, animations: { () -> Void in
                    
                    var temp = tipLab.frame
                    
                    temp.origin.y = 20.0
                    
                    tipLab.frame = temp
                    
                    
                    }, completion: { (Bool) -> Void in
                        
                        
                        tipLab.removeFromSuperview()
                        
                })
            
        })

    }

}



//实现数据源方法
extension YDHomeViewController{

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return YDHomeViewModel.shareInstance.StatusModels.count
        
        
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("home", forIndexPath: indexPath) as! YDUserStatusViewCell
        
        
        let model = YDHomeViewModel.shareInstance.StatusModels[indexPath.row]
        
        
        cell.model = model
        
        //当上拉加载更多的时候，当显示倒数第一个数据的时候开始新一轮的加载数据
        
        if indexPath.row == YDHomeViewModel.shareInstance.StatusModels.count - 1 {
        
       
            
            //让菊花再次转动
            loadingView.startAnimating()
            
            loadWeiBoData()
        
        
        }
        
        
        
        return cell
  
        
    }
    
    
    
    



}
